<script setup lang="ts">
import { VideoPlay, VideoPause } from '@element-plus/icons-vue'
import APIUploadMaterial from '@/api/upload-material'
import type { Props, Emits } from './utils/types'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useAuth } from '@/stores/index'
import { formatBytes } from '@/utils/index'
import type { FormRules, FormInstance } from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'

const $router = useRouter()
const $props = defineProps<Props>()
const $emit = defineEmits<Emits>()
const isPlay = shallowRef<boolean>(false)
const { info } = storeToRefs(useAuth())
const audioRef = shallowRef<any>()

watch(isPlay, (newValue) => {
    if (newValue) {
        audioRef.value?.play()
        audioRef.value.addEventListener('ended', () => {
            isPlay.value = false
        })
    } else {
        audioRef.value?.pause()
    }
})

function handleDelete(goods_id?: number) {
    if (!goods_id) return
    ElMessageBox.confirm(
        '是否删除该音乐？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        return APIUploadMaterial.deleteMusic(goods_id)
    }).then(() => {
        ElMessage.success('删除成功')
        $emit('get-is-pus')
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

function handleShowDialogVisible(item: any) {
    if (!info.value.shop_id) {
        ElMessageBox.confirm(
            '暂未入驻店铺，是否前往入驻店铺？',
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            $emit('close')
            $router.push({
                name: 'Store'
            })
        }).catch(() => { })
        return
    }
    const { goods_id } = item
    musicGetEditSDetail(goods_id)
    dialogVisible.value = true
}

const formData = ref<any>({
    profit: 50
})
const editSDetail = ref<any>({})

function musicGetEditSDetail(goods_id: number) {
    APIUploadMaterial.musicGetEditSDetail(goods_id).then(({ data }) => {
        editSDetail.value = data
        formData.value.goods_id = goods_id
        formData.value.authors = JSON.parse(JSON.stringify(editSDetail.value.AuthorList))
        formData.value.title = data.title
        if (editSDetail.value.status == 2) {
            formData.value.title = editSDetail.value.title
            formData.value.brief = editSDetail.value.brief
            formData.value.key = editSDetail.value.key
            formData.value.profit = editSDetail.value.profit
            formData.value.genre = editSDetail.value.genre_id
            formData.value.emotion = editSDetail.value.emotion_id
            formData.value.musical = editSDetail.value.musical_id
            formData.value.beat = editSDetail.value.beat_id
            formData.value.duration = editSDetail.value.duration_id
        }
    })
}

const dialogVisible = shallowRef<boolean>(false)

function handleClose() {
    dialogVisible.value = false
}

const dialogInnerVisible = shallowRef<boolean>(false)


function handlePriceClear() {
    formData.value.authors.forEach((item: any) => {
        item.market_price = 0
        item.get_price = 0
    })
}

function handlePriceAuto() {
    formData.value.authors.forEach((item: any, index: number) => {
        if (!editSDetail.value.AuthorList) return
        item.market_price = editSDetail.value?.AuthorList[index]?.market_price
        item.get_price = editSDetail.value?.AuthorList[index]?.get_price
    })
}

const rules = reactive<FormRules<any>>({
    title: [{
        required: true, message: '请输入标题', trigger: 'blur',
    }, {
        max: 40, message: '标题不可以超过40字', trigger: 'blur'
    }],
    brief: [{
        required: true, message: '请输入描述', trigger: 'blur'
    }, {
        max: 200, message: '作品介绍不可以超过40字', trigger: 'blur'
    }],
    key: [{
        required: true, message: '请输入关键字', trigger: 'blur'
    }, {
        pattern: /^([\u4e00-\u9fa5a-zA-Z0-9]+)(\/[\u4e00-\u9fa5a-zA-Z0-9]+){4,}$/,
        message: '不可少于5个关键词，并且不可有特殊符号',
        trigger: 'blur'
    }],
    genre: [{
        required: true, message: '请选择曲风', trigger: 'blur'
    }],
    emotion: [{
        required: true, message: '请选择情绪', trigger: 'blur'
    }],
    musical: [{
        required: true, message: '请选择乐器', trigger: 'blur'
    }],
    beat: [{
        required: true, message: '请选择节拍', trigger: 'blur'
    }],
    duration: [{
        required: true, message: '请选择时长', trigger: 'blur'
    }],
    profit: [{
        required: true, message: '请选择利润', trigger: 'blur'
    }]
})




const ruleFormRef = shallowRef<FormInstance>()

function submitChange() {
    ruleFormRef.value?.validate((valid, fields) => {
        if (valid) {
            const form = { ...formData.value }
            form.authors = JSON.stringify(form.authors)
            form.shop_id = info.value.shop_id
            const loading = ElLoading.service({ lock: true })
            APIUploadMaterial.changeMusic(form).then(({ msg }) => {
                ElMessage.success('提交成功')
                handleClose()
                $emit('get-is-pus')
            }).finally(() => {
                loading.close()
            })
        } else {
            if (fields?.title && fields?.title?.length != 0) {
                ElMessage.error(fields?.title[0]?.message)
            } else if (fields?.brief && fields?.brief?.length != 0) {
                ElMessage.error(fields?.brief[0]?.message)
            } else if (fields?.key && fields?.key?.length != 0) {
                ElMessage.error(fields?.key[0]?.message)
            } else if (fields?.genre && fields?.genre?.length != 0) {
                ElMessage.error(fields?.genre[0]?.message)
            } else if (fields?.emotion && fields?.emotion?.length != 0) {
                ElMessage.error(fields?.emotion[0]?.message)
            } else if (fields?.musical && fields?.musical?.length != 0) {
                ElMessage.error(fields?.musical[0]?.message)
            } else if (fields?.beat && fields?.beat?.length != 0) {
                ElMessage.error(fields?.beat[0]?.message)
            } else if (fields?.duration && fields?.duration?.length != 0) {
                ElMessage.error(fields?.duration[0]?.message)
            } else if (fields?.profit && fields?.profit?.length != 0) {
                ElMessage.error(fields?.profit[0]?.message)
            }
        }
    })
}

/** 监听函数防抖 */
let timer: number | null = null
watch(() => formData.value.title, (newValue) => {
    if (timer !== null) {
        clearTimeout(timer)
    }
    timer = setTimeout(() => {
        if (newValue) {
            APIUploadMaterial.getKey(newValue).then(({ data }) => {
                formData.value.key = data.join('/')
            })
        }
    }, 1000)
})
function handleJumpView(type: string, mark: string) {
    window.open(`${import.meta.env.VITE_APP_WEB_URL}/agreement?type=${type}&mark=${mark}`)
}

function handleFree() {
    formData.value.authors.forEach((item: any) => {
        item.get_price = 0
    })
}

</script>

<template>
    <div class="push-item">
        <img v-if="item.main_image" :src="item.main_image" alt="图片">
        <audio ref="audioRef">
            <source :src="item.sample" type="audio/mp3" />
        </audio>
        <div class="push-item-mask" v-if="item.is_push != 2">
            <div class="push-item-play">
                <el-icon size="60px" style="cursor: pointer;" color="#ffffff" v-show="!isPlay" @click="isPlay = true">
                    <VideoPlay />
                </el-icon>
                <el-icon size="60px" style="cursor: pointer;" color="#ffffff" v-show="isPlay" @click="isPlay = false">
                    <VideoPause />
                </el-icon>
            </div>
            <div class="push-item-btns">
                <span @click="handleShowDialogVisible(item)">编辑</span>
                <span @click="handleDelete(item.goods_id)">删除</span>
            </div>
        </div>
        <div class="is-push" v-else>公司审核中...</div>
    </div>
    <el-dialog v-model="dialogVisible" title="音乐作品编辑" width="1124" :before-close="handleClose" destroy-on-close
        :show-close="false">
        <template #header>
            <DialogClose title="音乐作品编辑" @close="handleClose" />
        </template>
        <el-dialog class="zuoping-edit" v-model="dialogInnerVisible" width="1000" :show-close="false">
            <template #header>
                <DialogClose title="音乐价格编辑" @close="dialogInnerVisible = false" />
                <EditQuestionFilled style="position: absolute; top: 11px; left: 98px;" />
            </template>
            <el-table class="price-edit" :data="formData.authors">
                <el-table-column label="板块">音乐</el-table-column>
                <el-table-column prop="using_body" label="授权类型" />
                <el-table-column label="授权详情信息（授权信息可编辑）" min-width="400" v-slot="{ row }">
                    <div v-if="!row.isShowAuthDetilEdit">
                        {{ row.auth_detail }}
                        <el-icon color="#0F40F5" size="20" style="cursor: pointer; position: relative; top: 4px;"
                            @click="row.isShowAuthDetilEdit = true">
                            <EditPen />
                        </el-icon>
                    </div>
                    <el-input v-model="row.auth_detail" v-else :ref="(el: any) => el?.focus()"
                        @blur="row.isShowAuthDetilEdit = undefined" />
                </el-table-column>
                <el-table-column label="市场价（元）" min-width="100" v-slot="{ row }">
                    <div v-if="!row.isShowMarketPriceEdit">
                        {{ row.market_price }}
                        <el-icon color="#0F40F5" size="20" style="cursor: pointer;position: relative;top: 4px;"
                            @click="row.isShowMarketPriceEdit = true">
                            <EditPen />
                        </el-icon>
                    </div>
                    <el-input v-model="row.market_price" v-else :ref="(el: any) => el?.focus()"
                        @blur="row.isShowMarketPriceEdit = undefined" />
                </el-table-column>
                <el-table-column label="到手价（元）" min-width="100" v-slot="{ row }">
                    <div v-if="!row.isShowGetPriceEdit">
                        {{ row.get_price }}
                        <el-icon color="#0F40F5" size="20" style="cursor: pointer;position: relative;top: 4px;"
                            @click="row.isShowGetPriceEdit = true">
                            <EditPen />
                        </el-icon>
                    </div>
                    <el-input v-model="row.get_price" v-else :ref="(el: any) => el?.focus()"
                        @blur="row.isShowGetPriceEdit = undefined" />
                </el-table-column>
            </el-table>
            <div class="price-edit-btn">
                <button type="button" style="background-color: #e6a23c" @click="handleFree">免费售卖</button>
                <button type="button" @click="handlePriceClear">清除价格</button>
                <button type="button" @click="handlePriceAuto">使用模板价格</button>
            </div>
            <button class="price-edit-submit" @click="dialogInnerVisible = false">
                确认
            </button>
        </el-dialog>
        <div class="no-pass" v-if="editSDetail.status == 2">
            不通过原因：{{ editSDetail.reason }}
        </div>
        <div class="picture-edit">
            <div class="left">
                <img v-if="editSDetail.main_image" :src="editSDetail.main_image" alt="main_image">
                <div class="bottom-image">
                    <img v-if="editSDetail.score" :src="editSDetail.score" alt="score">
                    <img v-if="editSDetail.copyright_image" :src="editSDetail.copyright_image" alt="copyright_image">
                </div>
            </div>
            <el-form class="form" ref="ruleFormRef" :model="formData" :rules="rules" :show-message="false">
                <div class="middle">
                    <div class="picture-info">
                        <div>编号：{{ editSDetail.code }}</div>
                        <div>日期：{{ editSDetail.create_time }}</div>
                        <div>大小：{{ formatBytes(Number(editSDetail?.file_size)) }}</div>
                    </div>
                    <div class="item-input">
                        <el-form-item prop="title" style="margin: 0;width: 100%;">
                            <el-input v-model="formData.title" placeholder="标题：请输入不超过40字的标题" style="height: 40px;"
                                input-style="font-family: 'SOURCEHANSANSCN-EXTRALIGHT'" />
                        </el-form-item>
                    </div>
                    <div class="text">准确描述产品将更易被搜索出来；<span @click="handleJumpView('help', 'title')">标题填写技巧</span></div>
                    <div class="item-input">
                        <el-form-item prop="brief" style="margin: 0;width: 100%;">
                            <el-input v-model="formData.brief" placeholder="描述：请输入不超过200字的作品介绍" type="textarea"
                                input-style="font-family: 'SOURCEHANSANSCN-EXTRALIGHT'" />
                        </el-form-item>
                    </div>
                    <div class="text">通过描述吸引更多感兴趣的用户；<span @click="handleJumpView('help', 'breif')">描述填写技巧</span></div>
                    <div class="item-input">
                        <el-form-item prop="key" style="margin: 0;width: 100%;">
                            <el-input v-model="formData.key" placeholder="不少于5个关键词，关键词与关键词以《 / 》符号隔开；"
                                style="height: 40px;" input-style="font-family: 'SOURCEHANSANSCN-EXTRALIGHT'" />
                        </el-form-item>
                    </div>
                    <div class="text">可快速使用关键词查找到作品；<span @click="handleJumpView('help', 'keyword')">关键词填写技巧</span>
                    </div>
                </div>
                <div class="right">
                    <div class="market-select">
                        <el-form-item label="曲风:" style="margin: 0;width: 100%;margin-bottom: 20px;" prop="genre">
                            <el-select v-model="formData.genre" placeholder="曲风">
                                <el-option v-for="item in editSDetail.genre" :key="item.id" :label="item.title"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="情绪:" style="margin: 0;width: 100%;margin-bottom: 20px;" prop="emotion">
                            <el-select v-model="formData.emotion" placeholder="情绪">
                                <el-option v-for="item in editSDetail.emotion" :key="item.id" :label="item.title"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="乐器:" style="margin: 0;width: 100%;margin-bottom: 20px;" prop="musical">
                            <el-select v-model="formData.musical" placeholder="乐器">
                                <el-option v-for="item in editSDetail.musical" :key="item.id" :label="item.title"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="节拍:" style="margin: 0;width: 100%;margin-bottom: 20px;" prop="beat">
                            <el-select v-model="formData.beat" placeholder="节拍">
                                <el-option v-for="item in editSDetail.beat" :key="item.id" :label="item.title"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="时长:" style="margin: 0;width: 100%;margin-bottom: 20px;" prop="duration">
                            <el-select v-model="formData.duration" placeholder="时长">
                                <el-option v-for="item in editSDetail.duration" :key="item.id" :label="item.title"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="market-price">
                        <div class="item-input">
                            <button type="button" @click="dialogInnerVisible = true">编辑授权及价格</button>
                        </div>
                        <p>按照授权类型填写销售价格</p>
                    </div>
                    <div class="market-price">
                        <div class="item-input">
                            <el-form-item prop="profit" style="margin: 0;width: 100%;">
                                <el-select v-model="formData.profit" placeholder="利润">
                                    <el-option v-for="(item, index) in editSDetail.profit_percentage" :key="index"
                                        :label="item.type" :value="item.title">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <p>选择销售出去作品分给平台的利润</p>
                    </div>
                </div>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false" style="width: 216px; height: 40px;">取消</el-button>
                <el-button color="rgb(15 64 240)" @click="submitChange" style="width: 216px; height: 40px;">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<style lang="scss">
.price-edit {
    .el-table__header {
        .cell {
            font-family: 'SOURCEHANSANSCN-REGULAR';
        }
    }

    .el-table__body-wrapper {
        .cell {
            font-family: 'SOURCEHANSANSCN-LIGHT';
        }
    }
}
</style>
<style lang="scss" scoped>
.no-pass {
    position: absolute;
    top: 11px;
    left: 135px;
    color: red;
    font-weight: 700;
}

.picture-edit {
    display: flex;
    justify-content: center;
    gap: 0 22px;
    margin-top: 30px;

    .right {
        width: 232px;

        .item-input {
            display: flex;

            &::before {
                content: '*';
                margin-right: 5px;
                font-size: 20px;
                font-weight: 700;
                color: #F91B1B;
            }
        }

        .market-select {
            margin-bottom: 20px;
        }

        .market-price {
            button {
                width: 231px;
                height: 40px;
                border-radius: 5px;
                background-color: rgba(15, 64, 245, 1);
                color: rgba(255, 255, 255, 1);
                font-size: 14px;
                border: none;
                cursor: pointer;
            }

            p {
                color: rgba(154, 154, 154, 1);
                font-size: 14px;
                margin-bottom: 20px;
                margin-left: 15px;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }
        }
    }

    .middle {
        width: 500px;

        .item-input {
            display: flex;

            &::before {
                content: '*';
                margin-right: 5px;
                font-size: 20px;
                font-weight: 700;
                color: #F91B1B;
            }
        }

        .text {
            margin-left: 20px;
            color: rgba(154, 154, 154, 1);
            font-size: 14px;
            line-height: 1.6em;
            margin-bottom: 20px;
            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';

            span {
                color: #3F90F7;
                cursor: pointer;
            }
        }

        .picture-info {
            display: flex;
            gap: 0 10px;
            margin-bottom: 20px;
        }
    }

    .form {
        display: flex;
        gap: 0 22px;
    }

    .left {
        width: 256px;
        height: 256px;
        background-color: #eeeeee;

        .bottom-image {
            display: flex;

            img {
                width: 128px;
                display: block;
                height: 85px;
                object-fit: cover;
            }
        }

        >img {
            display: block;
            width: 100%;
            height: 256px;
            object-fit: contain;
        }
    }
}

.price-edit-submit {
    width: 230px;
    height: 40px;
    border-radius: 5px;
    background-color: rgba(249, 20, 20, 1);
    color: rgba(255, 255, 255, 1);
    font-size: 14px;
    border: none;
    display: block;
    margin: 0 auto;
    cursor: pointer;
    margin-bottom: 40px;
    margin-top: 20px;
}

.price-edit-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 17px;
    gap: 0 26px;

    button {
        display: block;
        width: 120px;
        height: 40px;
        color: #ffffff;
        background-color: #3F90F7;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 14px;
    }
}

.price-edit {
    width: 100%;
    margin-top: 20px;
}

.push-item {
    position: relative;
    border-radius: 5px;
    height: 200px;
    overflow: hidden;

    .is-push {
        width: 100%;
        height: 100%;
        border-radius: 5px;
        background-color: rgba(0, 0, 0, 0.292);
        position: absolute;
        top: 0;
        left: 0;
        text-align: center;
        line-height: 200px;
        color: #ffffff;
    }

    &:hover .push-item-mask {
        opacity: 1;
    }

    .push-item-mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.292);
        opacity: 0;
        transition: all .2s;

        .push-item-play {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 135px;
        }

        .push-item-btns {
            box-sizing: border-box;
            width: 100%;
            height: 30px;
            color: #ffffff;
            font-size: 13px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 40px;

            span {
                cursor: pointer;
            }
        }
    }




    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

}
</style>
